package com.ksd.modules.upload.controller;

import com.ksd.common.controller.BaseController;
import com.ksd.modules.upload.model.FilePathPO;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class UploadController extends BaseController {


    @PostMapping(value = "/upload/uploadFile", consumes = {"multipart/form-data"})
    public String uploadFile(@RequestPart("file") MultipartFile file) {
        String userDir = System.getProperty("user.dir");
        String filePath = "";
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = dateFormat.format(new Date());
            // 生成唯一的文件名(UUID)
            String fileName = UUID.randomUUID().toString();
            // 获取文件的原始名称
            String originalFileName = file.getOriginalFilename();
            if (!StringUtils.isEmpty(originalFileName)) {
                // 获取文件扩展名
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                // 拼接文件名和扩展名
                fileName += fileExtension;
            }
            try {
                // 构建文件保存路径
                String savePath = userDir + File.separator + "files" + File.separator + currentDate + File.separator + fileName;
                // 创建目录
                File directory = new File(savePath).getParentFile();
                if (!directory.exists()) {
                    directory.mkdirs();
                }

                // 保存文件到本地磁盘
                file.transferTo(new File(savePath));
                // 将保存后的文件路径添加到列表中
                filePath = "files" + File.separator + currentDate + File.separator + fileName;
            } catch (Exception e) {
                e.printStackTrace();
            }
        return filePath;
    }

    @PostMapping(value = "/upload/uploadFiles", consumes = {"multipart/form-data"})
    public List<String> uploadFiles(@RequestPart("file") List<MultipartFile> files) {
        String userDir = System.getProperty("user.dir");
        List<String> filePaths = new ArrayList<>();
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = dateFormat.format(new Date());
        for (MultipartFile file : files) {
            // 生成唯一的文件名(UUID)
            String fileName = UUID.randomUUID().toString();
            // 获取文件的原始名称
            String originalFileName = file.getOriginalFilename();
            if (!StringUtils.isEmpty(originalFileName)) {
                // 获取文件扩展名
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
                // 拼接文件名和扩展名
                fileName += fileExtension;
            }
            try {
                // 构建文件保存路径
                String savePath = userDir + File.separator + "files" + File.separator + currentDate + File.separator + fileName;
                // 创建目录
                File directory = new File(savePath).getParentFile();
                if (!directory.exists()) {
                    directory.mkdirs();
                }

                // 保存文件到本地磁盘
                file.transferTo(new File(savePath));
                // 将保存后的文件路径添加到列表中
                filePaths.add("files" + File.separator + currentDate + File.separator + fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return filePaths;
    }


    /**
     * 获取文件流
     */
    @PostMapping("/upload/getFiles")
    public void getApprovalFormFile(@RequestBody FilePathPO filePathPO, HttpServletResponse response){
        String filePath = filePathPO.getFilePath();
        String userDir = System.getProperty("user.dir");
        FileInputStream in = null;
        try {
            in = new FileInputStream(userDir + File.separator+filePath);
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath.substring(filePath.lastIndexOf("\\")+1));
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.copy(in, response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
